﻿using Common;
using Http;
using Log4_Net;
using Microsoft.Extensions.Logging;
using NoticeCorpWechat.interfaces;
using NoticeCorpWechat.result;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NoticeCorpWechat
{
    public class MessageHelper : IMessageHelper
    {
        IHttpClientHelper _httpClientHelper;
        ILogger _ILogger;
        public MessageHelper(IHttpClientHelper httpClientHelper, ILogHelper logHelper)
        {
            _httpClientHelper = httpClientHelper;
            _ILogger = logHelper.GetLogger();
        }

        public async Task<EnumResult> Send(string token, string data)
        {
            try
            {
                var result = await _httpClientHelper.PostAsync($"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}", data);
                if (result.NotNullOrEmpty())
                {
                    var res = result.JsonToObject<MessageResult>();
                    if (res.errcode == 0 || res.errmsg == "ok")
                        return EnumResult.成功;
                    if (res.errcode == 42001)//token过期
                    {
                        return EnumResult.重试;//重试
                    }
                }
            }
            catch (Exception ex)
            {
                _ILogger.LogError(ex.Message + ex.StackTrace);
            }
            return EnumResult.失败;

        }
    }
}
